package org.esgi.util.xml;

import java.io.File;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.w3c.dom.Document;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSParser;

public class Stylizer
{
	private File xmlFile_;
	private DOMImplementationLS impl_;
	
	public Stylizer() 
	{
		try 
		{
			DOMImplementationRegistry ir  = DOMImplementationRegistry.newInstance();
			this.impl_ = (DOMImplementationLS) ir.getDOMImplementation("LS 3.0");
		} 
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	public Stylizer(File xmlFile)
	{
		this();
		this.setXmlFile(xmlFile);
	}
	
	public File getXmlFile() {
		return xmlFile_;
	}

	public void setXmlFile(File xmlFile) {
		this.xmlFile_ = xmlFile;
	}
	
	public void applyXsl(File xslFile)
	{
		this.applyXsl(xslFile, null);
	}
	
	public void applyXsl(File xslFile, File xmlOutputFile)
	{
		File xmlFile = this.getXmlFile();
		if(xmlFile != null && xslFile != null)
		{
			LSParser lsp = this.impl_.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);
			Document root = lsp.parseURI(xmlFile.getAbsolutePath());
			if(root != null)
			{
				TransformerFactory tFactory = TransformerFactory.newInstance();
	            StreamSource stylesource = new StreamSource(xslFile);
	            DOMSource source = new DOMSource(root);
	            StreamResult result = null;
	            if(xmlOutputFile != null)
	            	result = new StreamResult(xmlOutputFile);
	            else
	            	result = new StreamResult(System.out);
				try 
				{
					Transformer transformer = tFactory.newTransformer(stylesource);
		            transformer.transform(source, result);
				} 
				catch (Exception e) 
				{
					e.printStackTrace();
				}
			}
		}		
	}
}
